/**
  * Author: Mei
  * Date: 2020-11-20 14:10
  * Description: 
  *
  */
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <iostream>

class ThreadPool {
public:
    ThreadPool(size_t);

    //std::result_of<S(char, int&)>::type foo = 3.14; // 使用这样的写法会推导出模板参数中函数的返回值类型
    template<class F, class... Args>
    auto enqueue(F &&f, Args &&... args)
    -> std::future<typename std::result_of<F(Args...)>::type>;

    ~ThreadPool();

private:
    // //需要跟踪线程，以便我们可以加入它们
    std::vector<std::thread> workers;
    // /任务队列
    std::queue<std::function<void()> > tasks;

    // 同步
    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop;
};

// //构造函数只是启动了一些工人
inline ThreadPool::ThreadPool(size_t threads)
        : stop(false) {
    for (size_t i = 0; i < threads; ++i)
        workers.emplace_back( //线程体
                [this] {
                    for (;;) {
                        std::function<void()> task;

                        {
                            std::unique_lock<std::mutex> lock(this->queue_mutex);
                            this->condition.wait(lock,
                                                 [this] { return this->stop || !this->tasks.empty(); });
                            if (this->stop && this->tasks.empty())
                                return;
                            task = std::move(this->tasks.front());
                            this->tasks.pop();
                        }
                        task();
                    }
                }
        );
}

// 将新的工作项添加到池中
template<class F, class... Args>
auto ThreadPool::enqueue(F &&f, Args &&... args)
-> std::future<typename std::result_of<F(Args...)>::type> {
    //定义函数的返回值类型  只要加了::就需要加上typename 帮助编译器去确认
    using return_type = typename std::result_of<F(Args...)>::type;

    //类似调用函数
    //创建智能指针对象packaged_task  指定执行函数的返回值类型
    // 然后bind后面为执行参数类型 返回的是一个packaged_task类型的对象
    //可以分开写
    //std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
    //auto task = std::make_shared<std::packaged_task<return_type()> >(func);

    //packaged_task<return_type()>中指明返回值类型和形参
    auto task = std::make_shared<std::packaged_task<return_type()> >(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<return_type> res = task->get_future();
    {
        std::unique_lock<std::mutex> lock(queue_mutex);

        // 停止池后不允许排队
        if (stop)
            throw std::runtime_error("enqueue on stopped ThreadPool");
        //也可以分开写
        //std::function<void()> wrapper_func = [task]() {
        //    (*task)();
        //};
        //tasks.emplace(wrapper_func);
        tasks.emplace([task]() { (*task)(); });
    }
    condition.notify_one();
    return res;
}

// 析构函数加入所有线程
inline ThreadPool::~ThreadPool() {
    {
        std::unique_lock<std::mutex> lock(queue_mutex);
        stop = true;
    }
    condition.notify_all();
    for (std::thread &worker: workers)
        worker.join();
}

#endif